//- Copyright (C) 2023 Beijing Huaxia Chunsong Technology Co., Ltd. 
//- <https://www.chatopera.com>, Licensed under the Chunsong Public 
//- License, Version 1.0  (the "License"), https://docs.cskefu.com/licenses/v1.html
//- Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.
//- Copyright (C) 2018-Jun. 2023 Chatopera Inc, <https://www.chatopera.com>
//- Licensed under the Apache License, Version 2.0
//- http://www.apache.org/licenses/LICENSE-2.0
extends /apps/entim/include/layout.pug

block content
    #containter.clearfix(style='margin-right:200px;')
        .content-left
            .chat-above#above
                .clearfix.message.connect-message
                    span#connect-message(style='background-color:#FFFFFF;color:#4665d4;')
                        a(href='javascript:getMoreMessage()', style='color:#4665d4;')
                            i.layui-icon 
                            | 查看更多消息
                include /apps/entim/more.pug

                // 			<#if chatMessageList?? && chatMessageList.content>
                // 			<#list chatMessageList.content?reverse as chatMessage>
                // 				<#if chatMessage.calltype == "呼出">
                // 					<div class="clearfix chat-block">
                // 						<div class="chat-right">
                // 							<img class="user-img" src="/im/img/user.png" alt="">
                // 							<div class="chat-message">
                // 								<label class="time">${chatMessage.createtime!''}</label>
                // 								<label class="user">${user.uname!''}</label>
                // 							</div>
                // 							<div class="chatting-right">
                // 								<i class="arrow"></i>
                // 								<div class="chat-content">${(chatMessage.message!'')?no_esc}</div>
                // 							</div>
                // 						</div>
                // 					</div>
                // 				<#else>
                // 					<div class="clearfix chat-block">
                // 						<div class="chat-left">
                // 							<img class="user-img" src="/im/img/user.png" alt="">
                // 							<div class="chat-message">
                // 								<label class="user">${entimuser.uname!''}</label>
                // 								<label class="time">${chatMessage.createtime!''}</label>
                // 							</div>
                // 							<div class="chatting-left">
                // 								<i class="arrow"></i>
                // 								<div class="chat-content">${(chatMessage.message!'')?no_esc}</div>
                // 							</div>
                // 						</div>
                // 					</div>
                // 				</#if>
                // 			</#list>
                // 			</#if>
            .chat-bottom#bottom
                textarea#message(name='content', style='visibility:hidden;')
                .btn-push.clearfix
                    #surplus(style='float:left;height:24px;line-height:34px;margin: 5px 20px 10px 5px;') 0/200
                    div(style='display: inline-block;position: absolute;right: 110px;bottom: 14px;') Ctrl + Enter
                    button.send-btn.active.special.clearfix#sent(type='button', onclick='sendMessage()', style='background-color:#32c24d;font-weight: 200;padding:5px;')
                        | 发送
        .content-rig
            .content-head
                p 用户信息
            .content-list
                ul
                    li
                        p
                            | 姓名：#{entimuser.uname}
                    if organ
                        li
                            p
                                | 部门：#{organ.name}
                    li
                        p
                            | 邮件：#{entimuser.email}
                    li
                        p
                            | 电话：#{entimuser.mobile}
                    li
                        p
                            | 部门：
                            if organs
                                for organ in organs
                                    organ.name &nbsp
            .content-bottom
                span#welcome-message
                    p 欢迎使用春松客服企业聊天
                    p
                        | QQ群：
                        a(target='_blank', href='//shang.qq.com/wpa/qunwpa?idkey=ef3061d99653e2f43619ddcefbf76ac2399196d89fd589501e19ae64423a5a31')
                            img(border='0', src='//pub.idqqimg.com/wpa/images/group.png', alt='春松客服开源社区', title='春松客服开源社区')
                    p
                        | 详情请咨询：
                        a(href='https://www.chatopera.com', target='_blank', style='color:#32c24d;') 春松客服
    style.
        .ukefu-media-image {
            max-height: 150px;
            max-width: 200px;
            cursor: pointer;
        }
    script(type='text/javascript').
        var editor, words;
        KindEditor.ready(function (K) {
            editor = K.create('textarea[name="content"]', {
                autoHeightMode: false,
                width: "100%",
                resizeType: 0,
                themeType: 'simple',
                fontsize: 14,
                newlineTag: "br",
                filterMode: true,
                items: ['emoticons', 'image', 'insertfile'],
                uploadJson: '/ent/im/image/upload.html?userid=#{entimuser.id}',
                filePostName: 'imgFile',
                allowImageRemote: false,
                allowFileUpload: true,
                allowInsertUpload: false,
                afterChange: function () {
                    var count = this.count();

                    words = this.count("text");
                    var pattern = '字数：' + words + '字';
                    document.getElementById('surplus').innerHTML = "字符： " + count + "  ，文字：" + pattern; //输入显示
                    ////////
                },
                afterCreate: function () { //设置编辑器创建后执行的回调函数
                    var self = this;
                    //Ctrl+Enter提交表单
                    K.ctrl(document, 13, function () {
                        self.sync();
                        sendMessage();
                    });
                    K.ctrl(self.edit.doc, 13, function () {
                        self.sync();
                        sendMessage();
                    });
                }
            });
        });
        KindEditor.options.cssData = "body { font-size: 15px; font-family:'Microsoft Yahei', 'Helvetica', 'Simsun', 'Arial';}";
        var R3Ajax = {
            ajax: function (opt) {
                var xhr = this.createXhrObject();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState != 4) return;
                    (xhr.status === 200 ?
                        opt.success(xhr.responseText, xhr.responseXML) :
                        opt.error(xhr.responseText, xhr.status));
                }
                xhr.open(opt.type, opt.url, true);
                if (opt.type !== 'post')
                    opt.data = null;
                else
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                opt.data = this.parseQuery(opt.data);
                xhr.send(opt.data);
            },
            post: function (url, success, data) {
                var popt = {
                    url: url,
                    type: 'post',
                    data: data,
                    success: success,
                    error: function (data) {
                    }
                }
                this.ajax(popt);
            },
            get: function (url, success) {
                var gopt = {
                    url: url,
                    type: 'get',
                    success: success,
                    error: function () {
                    }
                }
                this.ajax(gopt);
            },
            createXhrObject: function () {
                var methods = [
                    function () {
                        return new XMLHttpRequest();
                    },
                    function () {
                        return new ActiveXObject('Msxml2.XMLHTTP');
                    },
                    function () {
                        return new ActiveXObject('Microsoft.XMLHTTP');
                    }
                ];
                for (var i = 0; len = methods.length, i < len; i++) {
                    try {
                        methods[i]();
                    } catch (e) {
                        continue;
                    }
                    this.createXhrObject = methods[i];
                    return methods[i]();
                }
                throw new Error('Could not create an XHR object.');
            },
            parseQuery: function (json) {
                if (typeof json == 'object') {
                    var str = '';
                    for (var i in json) {
                        str += "&" + i + "=" + encodeURIComponent(json[i]);
                    }
                    return str.length == 0 ? str : str.substring(1);
                } else {
                    return json;
                }
            }
        };
        Date.prototype.format = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds()             //毫秒
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        }
        var R3Helper = {
            resize: function () {
                var height = document.body.offsetHeight;
                document.getElementById('above').style.height = (height - 194 - 50) + "px";
            }
        }
    script.
        layui.use('element', function () {
            var $ = layui.jquery
                , element = layui.element(); //Tab的切换功能，切换事件监听等，需要依赖element模块
        });
        var hostname = location.hostname;
        var socket = io.connect(location.protocol + "//" + top.hostname + ":" + top.port + "/im/ent?userid="+'#{user.id}'+ "&contextid="+'#{contextid}', {
            transports: ['websocket'],
            upgrade: false
        });
        socket.on('message', function (data) {
            if (data.contextid != "#{entimuser.id}") {
                return;
            }

            console.log('message', data);
            data.createtime = formatDate(data.createtime);
            var chat = document.getElementsByClassName('chatting-left').innerText;
            chat = data.message;

            if (data.msgtype == 'image') {
                chat = "<a href='" + data.message + "&original=true' target='_blank'><img src='" + data.message + "' class='ukefu-media-image'/></a>";
            } else if (data.msgtype == 'file') {
                chat = "<div class='ukefu-message-file'><div class='ukefu-file-icon'><img src='/im/img/file.png'></div><div class='ukefu-file-desc'><a href='" + data.message + "' target='_blank'><div>" + data.filename + "</div><div>" + (data.filesize / 1024).toFixed(3) + "Kb</div></a></div></div>";
            }

            if (data.calltype == "呼出") {
                output('<div class="chat-right"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label class="time">' + data.createtime + '</label><label  class="user">'+"#{user.uname}"+'</label> </div><div class="chatting-right"><i class="arrow"></i><div class="chat-content">' + chat + '</div></div>' , "chat-block"
            )
                ;
            } else if (data.calltype == "呼入") {
                output('<div class="chat-left"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label  class="user">'+"#{entimuser.uname}"+' </label><label class="time">' + data.createtime + '</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">' + chat + '</div></div>' , "chat-block"
            )
                ;
            }
        });
        socket.on('status', function (data) {
            if (data.contextid == '#{entimuser.id}') {
                if (data.message == 'online') {
                    top.$('#chat_#{entimuser.id}').removeClass('offline').removeClass('online').addClass('online').attr('title', '在线');
                } else if (data.message == 'offline') {
                    top.$('#chat_#{entimuser.id}').removeClass('online').removeClass('offline').addClass('offline').attr('title', '离线');
                }
            }
        })
        function sendMessage() {
            editor.sync();
            var count = editor.count("text");
            if (count > 0) {
                var message = document.getElementById('message').value;
                if (message != "") {
                    socket.emit('message', {
                        userid: "#{user.id}",
                        type: "message",
                        session: "#{user.id}",
                        touser: "#{entimuser.id}",
                        contextid: "#{user.id}",
                        message: message
                    });
                }
                editor.html('');
            }
        }
        function output(message, clazz) {
            if (clazz == "message connect-message") {
                var messages = document.getElementsByClassName("connect-message");
                for (inx = 0; inx < messages.length;) {
                    document.getElementById('above').removeChild(messages[inx]);
                    inx++;
                }
            }
            var element = ("<div class='clearfix " + clazz + "'>" + " " + message + "</div>");
            document.getElementById('above').innerHTML = (document.getElementById('above').innerHTML + element);
            document.getElementById('above').scrollTop = document.getElementById('above').scrollHeight;
        }
        document.getElementById('above').scrollTop = document.getElementById('above').scrollHeight;
        if('#{online && online == true}'){
            top.$('#chat_#{entimuser.id}').removeClass('offline').addClass('online').attr('title' , '在线');
        }

        function getMoreMessage() {
            var firstCreateTime = $('.time').first().text();
            R3Ajax.get("/ent/im/chat/more.html?userid=#{entimuser.id}&createtime=" + firstCreateTime, function (html) {
                $('.connect-message').after(html);
            });
        }

